﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Transactions;
using T.FAS.Runtime.DataModel.Dao;
using T.FAS.Runtime.Metadata.Entity.DataModel;
using T.FAS.Runtime.Metadata.Entity;
using Newtonsoft.Json;
using T.FAS.Runtime.Base.Entity;

namespace T.FAS.Runtime.DataModel.Dao
{
    /// <summary>
    /// DO元数据变更管理类
    /// </summary>
    public class DataObjectChangeManager
    {
        private readonly DataObjectELBDao _dataObjectELBDao = new DataObjectELBDao();
        private readonly CompositeDataObjectELBDao _compositeDataObjectELBDao = new CompositeDataObjectELBDao();

        private DataObjectCompareResult _compareResult = new DataObjectCompareResult();

        private DataObject newDO;

        private DataObject oldDO;

        public DataObjectChangeManager(DataObject newDataObject)
        {
            var DOId = newDataObject.MetaDataID ?? newDataObject.ID;
            oldDO = GetDataObjectFromDB(DOId);
            if (oldDO == null)
            {
                throw new FasException(DataModelErrorCode.NullValue, "DO变更失败，请检查DOId是否正确");
            }

            newDO = newDataObject;
        }

        public void Compare()
        {
            _compareResult = DataObjectChangeChecker.Compare(oldDO, newDO);
        }

        /// <summary>
        /// 依赖检查
        /// </summary>
        public void DependencyCheck()
        {
            /*
             * 依赖检测：
             * 1、是否被其它DO引用
             * 2、是否引用其它DO
             * 3、是否作为CDO主子节点树引用
             * 4、是否被CDO外键引用
             */
            var DoRs = _dataObjectELBDao.GetObjectsByFilter($"FromDOID='{oldDO.ID}'");

            var column = oldDO.Columns.Where(col => col.IsFkColumn);

            var cdo_inner = _compositeDataObjectELBDao.GetObjectsByFilter(
                $"ID IN(SELECT CompositeDataObjectID FROM FAS_CompositeNodeObject WHERE DataObjectID='{oldDO.ID}')"
                );
            var cdo_outer = _compositeDataObjectELBDao.GetObjectsByFilter(
                $"ID IN(SELECT CompositeDataObjectID FROM FAS_Association WHERE AssoDataObjectID='{oldDO.ID}')"
                );
        }
        
        private DataObject GetDataObjectFromDB(string doId)
        {
            return _dataObjectELBDao.GetDataObjectByID(doId);
        }
    }
}
